package routes

import (
	"log"
	"net/http"

	"gitee.com/realjf/wob/api"
	"gitee.com/realjf/wob/models"
	"gitee.com/realjf/wob/routes/middleware"
	"github.com/gin-gonic/gin"
)

func InitRouter(app *gin.Engine) {
	app.Use(middleware.Cors())

	app.POST("/api/v1/login", login)
	v1 := app.Group("/api/v1")
	{
		v1.POST("/p", api.Proto)
		v1.POST("/logout", logout)
	}
	v1.Use(auth)
}

func auth(c *gin.Context) {
	token := c.GetHeader("Authorization")

	verify, err := middleware.VerifyToken(token)
	if err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 199,
			"msg":  "验证token失败",
		})
		c.Abort()
		return
	}

	claims := models.Claims{}
	if err := verify.Claims(&claims); err == nil {
		c.Set("gin.jwt.claims", claims)
	}

	c.Next()
}

func login(c *gin.Context) {
	claims := models.Claims{}
	if err := c.BindJSON(&claims); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 199,
			"msg":  "缺少token",
		})
		return
	}

	// 验证用户

	//---------

	if jwtToken, err := middleware.GenerateToken(claims); err == nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 100,
			"data": jwtToken,
			"msg":  "登录token",
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 199,
		"msg":  "生成token失败",
	})
}

func logout(c *gin.Context) {
	claims, _ := c.Get("gin.jwt.claims")
	log.Println(c.FullPath(), claims.(models.Claims))
}
